package com.example.demo;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.client.RestTemplate;

import javax.servlet.http.HttpSession;

@Controller
public class IndexController {


    private final RestTemplate restTemplate = new RestTemplate();
    private final ObjectMapper mapper = new ObjectMapper();

    private String defaultCallback = "/";  // 默认callback
    private String ssoServerValidate = "http://106.15.179.107:7127/api/c/sso/validate-token"; // sso验证token地址
    private String ssoServerAuth = "http://106.15.179.107:7127/api/c/sso/auth"; // 如果本地应用没有登陆就去验证
    private String ssoServerLogout = "http://106.15.179.107:7127/api/c/sso/sign-out";
    private String ssoKey = "574163310";               // 本地应用密码
    private String appHost = "http://localhost:8000";  // 本地应用地址


    @GetMapping("/")
    public String index(HttpSession session, Model model) {

        Object userId = session.getAttribute("userId");

        //如果不为null则视为登陆，返回index页面
        if (userId != null) {
            model.addAttribute("userId", userId);
            return "index";
        }
        //否则跳转到登陆页面
        return "redirect:" + ssoServerAuth + "?callback=" + appHost;
    }


    //由sso系统调用
    @GetMapping("/api/c/sso/client/token")
    public String token(@RequestParam(name = "token") String token,
                        @RequestParam(name = "callback") String callback,
                        HttpSession session) throws JsonProcessingException {

        if (StringUtils.isEmpty(callback)) {
            callback = defaultCallback;
        }

        //拼接参数
        HttpHeaders headers = new HttpHeaders();
        headers.setContentType(MediaType.APPLICATION_JSON);
        ValidateTokenJson params = new ValidateTokenJson(ssoKey, token, appHost);
        HttpEntity<String> entity = new HttpEntity<String>(mapper.writeValueAsString(params), headers);

        String res = "";
        try {
            //向sso验证token是否合法
            res = restTemplate.postForObject(ssoServerValidate, entity, String.class);
            session.setAttribute("userId", res);
        } catch (Exception ex) {
            return "login error";
        }


        return "redirect:" + callback;
    }

    public class ValidateTokenJson {

        public ValidateTokenJson() {
        }

        public ValidateTokenJson(String key, String token, String origin) {
            this.key = key;
            this.token = token;
            this.origin = origin;
        }

        private String key;
        private String token;
        private String origin;

        public String getKey() {
            return key;
        }

        public void setKey(String key) {
            this.key = key;
        }

        public String getToken() {
            return token;
        }

        public void setToken(String token) {
            this.token = token;
        }

        public String getOrigin() {
            return origin;
        }

        public void setOrigin(String origin) {
            this.origin = origin;
        }
    }

    @GetMapping("/logout")
    public String logout(HttpSession session){
        // 自己先退出
        session.removeAttribute("userId");
        // 跳转到sso服务器退出
        return "redirect:" + ssoServerLogout + "?callback=" + appHost;
    }
}
